package com.yehongyu.mytools.toolkit.compress;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

public class DeCompress {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		DeCompress dec = new DeCompress();
		//读取文件地址
		String filePath = "D:/tempCom.txt";
		StringBuffer fileContent = new StringBuffer();
		String temp;
		try {
			BufferedReader file = new BufferedReader(new FileReader(filePath));
			while((temp = file.readLine()) != null) {
				fileContent.append(temp);
			}
			System.out.println("文件大小（K）："+fileContent.toString().getBytes().length/1024f);
			long pred = 0;
			long afterd = 0;
			byte[] b = null;
			byte[] c = fileContent.toString().getBytes();
			pred = System.currentTimeMillis();
			b = dec.compress(c);
			afterd = System.currentTimeMillis();
//			System.out.println("第"+(i+1)+"次压缩时间（豪秒）:"+(afterd-pred));
			
			long predall = System.currentTimeMillis();
			for(int i=0;i<1000;i++){	
				pred = System.currentTimeMillis();
				c = dec.decompress(b);
				if(c instanceof byte[])
					new String(c);
				afterd = System.currentTimeMillis();
				System.out.println("第"+(i+1)+"次解压时间（豪秒）:"+(afterd-pred));
			}
			long afterdall = System.currentTimeMillis();
			System.out.println("总共压缩解压时间（豪秒）:"+(afterdall-predall));
			System.out.println("压缩后 文件大小（K）："+b.length/1024f);
		}catch(Exception e){
			
		}

	}
	
	
	private byte[] compress(byte[] in) {
		if (in == null) {
			throw new NullPointerException("Can't compress null");
		}
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		GZIPOutputStream gz = null;
		try {
			gz = new GZIPOutputStream(bos);
			gz.write(in);
		} catch (IOException e) {
			throw new RuntimeException("IO exception compressing data", e);
		} finally {
			try {
				gz.close();
				bos.close();
			} catch (Exception e) {
				// should not happen
			}
		}
		byte[] rv = bos.toByteArray();
		return rv;
	}
    
    private byte[] decompress(byte[] in) {
		ByteArrayOutputStream bos = null;
		if (in != null) {
			ByteArrayInputStream bis = new ByteArrayInputStream(in);
			bos = new ByteArrayOutputStream();
			GZIPInputStream gis;
			try {
				gis = new GZIPInputStream(bis);

				byte[] buf = new byte[8192];
				int r = -1;
				while ((r = gis.read(buf)) > 0) {
					bos.write(buf, 0, r);
				}
			} catch (IOException e) {
				bos = null;
			}
		}
		return bos == null ? null : bos.toByteArray();
	}

}
